<?php

namespace App\Services;

use App\Models\Games;
use App\Models\SpinWheelLotteryLog;
use App\Models\SpinWheelUser;
use App\Models\UserExtend;
use App\Models\UserRoles;
use App\Models\Users;

class SpinWheelService extends ServiceBase
{
    /**
     * 获取抽奖规则
     */
    public function getRuleList($user)
    {
        $rule_list = [
            ['text' => '注册登录抽奖一次', 'status' => $user['reg_time'] > 0 ? 1 : 0],
            ['text' => '等级40级抽奖一次', 'status' => $user['role_level'] > 40 ? 1 : 0],
        ];

        $amount_list = [30, 198, 648];
        for ($i = 0; $i < 19; $i++) {
            $amount      = $i * 500 + 1000;
            $amount_list = array_merge($amount_list, [$amount]);
        }

        $temp_list = [];
        foreach ($amount_list as $val) {
            $status = 0;
            if ($user['total_pay_money'] >= $val) {
                $status = 1;
            }
            $temp_list[] = ['text' => "累充{$val}元抽奖一次", 'status' => $status];
        }

        return array_merge($rule_list, $temp_list);
    }

    /**
     * 抽奖
     */
    public function lottery($request)
    {
        $game_id = $request->input('game_id');
        $openid  = $request->input('openid');
        if (!$openid) {
            return 102;
        }

        $user = SpinWheelUser::where('openid', $openid)->first();
        if (!$user) {
            return 6004;
        }

        if ($user->lottery_num <= 0) {
            return 7022;
        }

        $total_pay_money = $user->total_pay_money;

        $prize_list = [
            ['name' => '高级扭蛋券*20', 'is_entity' => 0, 'pay_limit' => 0, 'odds' => 190],
            ['name' => 'BEOE爽肤水*1', 'is_entity' => 1, 'pay_limit' => 648,  'odds' => 1],
            ['name' => '至尊甄选盒*1', 'is_entity' => 0, 'pay_limit' => 0, 'odds' => 5],
            ['name' => '高级扭蛋券*10', 'is_entity' => 0, 'pay_limit' => 0,  'odds' => 480],
            ['name' => 'BEOE祛痘膏*1', 'is_entity' => 1, 'pay_limit' => 198,  'odds' => 1],
            ['name' => '闪光至尊任选盒*1', 'is_entity' => 0, 'pay_limit' => 198,  'odds' => 2],
            ['name' => '优惠券138-50*1', 'is_entity' => 0, 'pay_limit' => 0,  'odds' => 320],
            ['name' => 'BEOE洗面奶*1', 'is_entity' => 1, 'pay_limit' => 198, 'odds' => 1],
        ];

        //不符合条件的奖品概率加到第一个奖品里
        foreach ($prize_list as $key => $item) {
            if ($total_pay_money < $item['pay_limit']) {
                $prize_list[$key]['odds']  = 0;
                $prize_list[0]['odds']    += $item['odds'];
            }
        }

        //划分中奖区域
        $all         = 0;
        $reward_area = [];
        foreach ($prize_list as $k => $v) {
            if ($v['odds'] != 0) {
                $all             += $v['odds'];
                $reward_area[$k]  = $all;
            }
        }

        //生成随机数
        $rand_num = mt_rand(1, 1000);

        //确定中奖索引
        $prize_index = -1;
        foreach ($reward_area as $index => $val) {
            if ($rand_num <= $val) {
                $prize_index = $index;
                break;
            }
        }

        if ($prize_index < 0) {
            return 7023;
        }

        $user->used_lottery_num++;
        $user->lottery_num--;
        $user->save();

        $class              = new SpinWheelLotteryLog;
        $class->game_id     = $game_id;
        $class->openid      = $openid;
        $class->prize_name  = $prize_list[$prize_index]['name'];
        $class->is_entity   = $prize_list[$prize_index]['is_entity'];
        $class->name        = '';
        $class->phone       = '';
        $class->address     = '';
        $class->is_send     = 0;
        $class->create_time = time();
        $class->send_time   = 0;
        $class->save();

        return ['index' => $prize_index, 'logid' => $class->id];
    }

    /**
     * 获取奖品列表
     */
    public function getPrizeList()
    {
        $prize_list = [
            ['name' => '高级扭蛋券*20', 'value' => '320元', 'desc' => '介绍：可免费进行一次钻石扭蛋', 'is_entity' => 0],
            ['name' => 'BEOE爽肤水*1', 'value' => '338元', 'desc' => '介绍：BEOE调肤水，补水保湿提亮肤色，肌底维稳，淡化痘肌', 'is_entity' => 1],
            ['name' => '至尊甄选盒*1', 'value' => '500元', 'desc' => '介绍：可自选一只5星至尊神兽', 'is_entity' => 0],
            ['name' => '高级扭蛋券*10', 'value' => '160元', 'desc' => '介绍：可免费进行一次钻石扭蛋', 'is_entity' => 0],
            ['name' => 'BEOE祛痘膏*1', 'value' => '68元', 'desc' => '介绍：BEOE怯痘精华，清爽去痘，修复淡化痘印，早晚一抹，靶向净痘', 'is_entity' => 1],
            ['name' => '闪光至尊任选盒*1', 'value' => '1000元', 'desc' => '介绍：可自选一只闪光至尊宠物', 'is_entity' => 0],
            ['name' => '优惠券138-50*1', 'value' => '50元', 'desc' => '介绍：可在天猫BEOE旗舰店联系客服领取，购买138元以上商品时抵扣50元', 'is_entity' => 0],
            ['name' => 'BEOE洗面奶*1', 'value' => '88元', 'desc' => '介绍：BEOE氨基酸慕斯洗面奶，温和清洁不伤肤', 'is_entity' => 1],
        ];

        return $prize_list;
    }

    /**
     * 地址填写
     */
    public function addressFill($request)
    {
        $id = $request->input('logid');

        $class = SpinWheelLotteryLog::find($id);
        if (!$class) {
            return 7024;
        }

        $class->name = $request->input('name');
        $class->phone = $request->input('phone');
        $class->address = $request->input('address');

        $class->save();

        return 0;
    }

    /**
     * 获取抽奖日志
     */
    public function getLotteryLog($request)
    {
        return SpinWheelLotteryLog::where('openid', $request->input('openid'))->orderBy('create_time', 'DESC')->get()->toArray();
    }

    /**
     * 获取用户角色信息和累计充值金额
     */
    public function getUserBasicInfo($openid)
    {
        $first_reg_time = 0;
        $max_level = 0;
        $total_pay = 0;

        $game_list = Games::where('project_id', 6)->get()->toArray();
        $game_ids = array_column($game_list, 'game_id');

        $list = Users::whereRaw("channel_openid='{$openid}'")->get();
        foreach ($list as $user) {
            if (!in_array($user->game_id, $game_ids)) {
                continue;
            }
            // 总充值金额
            $extend = UserExtend::where('user_id', $user->user_id)->first();
            $total_pay += $extend->total_pay_amount;

            // 角色最早注册时间和最大等级
            $roles = UserRoles::where('user_id', $user->user_id)->get();
            foreach ($roles as $role) {
                if ($first_reg_time < 1 || $first_reg_time > $role->create_time) {
                    $first_reg_time = $role->create_time;
                }

                if ($max_level < 1 || $max_level < $role->role_level) {
                    $max_level = $role->role_level;
                }
            }
        }

        return [
            'openid'         => $openid,
            'first_reg_time' => $first_reg_time,
            'max_level'      => $max_level,
            'total_pay'      => $total_pay,
        ];
    }

    /**
     * 创建或更新抽奖用户
     */
    public function createOrUpdateUser($game_id, $openid)
    {
        $class = SpinWheelUser::where('openid', $openid)->first();
        if (!$class) {
            $class                   = new SpinWheelUser;
            $class->game_id          = $game_id;
            $class->openid           = $openid;
            $class->used_lottery_num = 0;
            $class->create_time      = time();
        }

        $role_info              = $this->getUserBasicInfo($openid);
        $class->role_level      = $role_info['max_level'];
        $class->total_pay_money = $role_info['total_pay'];
        $class->reg_time        = $role_info['first_reg_time'];

        $total_lottery_num = 0;

        if ($class->reg_time != 0) {
            $total_lottery_num += 1;
        }

        if ($class->role_level >= 40) {
            $total_lottery_num += 1;
        }

        $amount_list = [30, 198, 648];
        for ($i = 0; $i < 19; $i++) {
            $amount      = $i * 500 + 1000;
            $amount_list = array_merge($amount_list, [$amount]);
        }

        foreach ($amount_list as $val) {
            if ($class->total_pay_money >= $val) {
                $total_lottery_num += 1;
            }
        }

        $lottery_num = $total_lottery_num - $class->used_lottery_num;
        if ($lottery_num < 0) {
            $lottery_num = 0;
        }

        $class->total_lottery_num = $total_lottery_num;
        $class->lottery_num       = $lottery_num;
        $class->save();

        return $class->toArray();
    }
}
